1. Home
  2. Node.js
  3. Node.js Basics
  4. Node.js – Errors

Node.js – Errors

Node.js provides multiple ways for the propagating and handling errors occur during the Node.js application execution. The error reported by a Node.js application depends on the type of error. There are generally four types of errors in the Node.js application.

  • Standard JavaScript errors – Like
    • EvalError
    • SyntaxError
    • RangeError
    • ReferenceError
    • TypeError
    • URIError
  • System Error – For example attempt to open a file that does not exist, attempting to send data over a closed socket, etc;
  • User-specified Errors – These errors triggered by application code. Also can be known as human mistakes
  • Assertion Errors – These are a special class of error that can be triggered whenever Node.js detects an exceptional logic violation

Node.js Error Example 1

Below script tried to add the value of the variable i with an undefined variable j, which will return with an error of ReferenceError. Copy below script in node_error_example.js file-

and execute is as below

node node_error_example.js

[output]
ReferenceError: j is not defined
    at Object. (/root/myapp/error_example1.js:3:19)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

Node.js Error Example 2

The below script uses the fs module and tried to read a file, which does not really exist on the file system. Copy below script to a JavaScript file –

and execute it like below.

node node_error_example.js

[output]
Error found => { Error: ENOENT: no such file or directory, open '/path/to/file-not-exists'
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/path/to/file-not-exists' }
Tags , , ,